package com.imooc.demo.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONException;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;

/**
 * 手机型号保存的列表
 */
public class PhoneHelper {

    private PhoneHelper() {

    }

    private static final PhoneHelper instance = new PhoneHelper();

    public static PhoneHelper getInstance() {
        return instance;
    }

    private JSONObject phoneJsonObject = null;

    public JSONObject getPhoneJsonObject() {
        return phoneJsonObject;
    }

    public void setPhoneJsonObject(JSONObject phoneJsonObject) {
        this.phoneJsonObject = phoneJsonObject;
    }

    /**
     * @return 获得厂商列表
     */
    public ArrayList<String> getManufacturerList() {

        JSONObject phoneJsonObject = getPhoneJsonObject();
        if (phoneJsonObject == null) {
            try {
                reload();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        Iterator<String> stringIterator = getPhoneJsonObject().keySet().iterator();

        ArrayList<String> stringArrayList = new ArrayList<>();

        while (stringIterator.hasNext()) {
            JSONArray modelJsonArray = getPhoneJsonObject().getJSONArray(stringIterator.next());
            for (int i = 0; i < modelJsonArray.size(); i++) {
                JSONObject modelItem = modelJsonArray.getJSONObject(i);

                if (!stringArrayList.contains(modelItem.getString("manufacturer"))) {
                    stringArrayList.add(modelItem.getString("manufacturer"));
                }
            }
        }

        return stringArrayList;
    }

    public HashMap<String, String> getModelList(String manufacturerName) {
        HashMap<String, String> hashMap = new HashMap<>();

        Iterator<String> stringIterator = getPhoneJsonObject().keySet().iterator();
        while (stringIterator.hasNext()) {
            JSONArray modelJsonArray = getPhoneJsonObject().getJSONArray(stringIterator.next());
            for (int i = 0; i < modelJsonArray.size(); i++) {
                JSONObject modelItem = modelJsonArray.getJSONObject(i);

                if (modelItem.getString("manufacturer").equals(manufacturerName)) {
                    hashMap.put(modelItem.getString("name"), modelItem.getString("model"));
                }
            }
        }

        return hashMap;
    }

    public void reload() throws IOException, JSONException {

        setPhoneJsonObject(JSONObject.parseObject(FileUtils.readFileToString(new File("/learndev/javaee/demotest", "phone.json"), "UTF-8")));
    }


}
